package com.hc.util;

import com.hc.entity.UUser;
import io.jsonwebtoken.*;

import java.util.Base64;
import java.util.Date;

public class JWTUtil {
    public static final String ISSUER = "沙口";
    public static final String PRIVATE_KEY = Base64.getEncoder().encodeToString("呆子".getBytes());

    public static String createToken(String userName, String passWord, String subject, long expireMillis) {
        JwtBuilder builder = Jwts.builder();
        Date now = new Date();
        return builder.setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setIssuer(ISSUER)
                .setAudience(userName)
                .setSubject(subject)
                .claim("name", userName)
                .claim("password", passWord)
                .setIssuedAt(now)
                .setNotBefore(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expireMillis))
                .signWith(SignatureAlgorithm.HS256, PRIVATE_KEY)
                .compact();
    }


    public static String reassignToken(String oldToken) {
        UUser user;
        Claims claims;
        try {
            claims = getClaimFromToken(oldToken);
        } catch (ExpiredJwtException e) {
            claims = e.getClaims();
        }
        user = getUserFromClaims(claims);
        String subject = claims.getSubject();
        return createToken(user.getName(), user.getPassword(), subject, Constant.JWT_EXPIRE_TIME_MILLIS);
    }

    public static Claims getClaimFromToken(String token) {
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJwts = parser.setSigningKey(PRIVATE_KEY).parseClaimsJws(token);
        return claimsJwts.getBody();
    }

    public static UUser getUserFromToken(String token) {
        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJwts = parser.setSigningKey(PRIVATE_KEY).parseClaimsJws(token);
        Claims claims = claimsJwts.getBody();
        return getUserFromClaims(claims);
    }

    public static UUser getUserFromClaims(Claims claims) {
        UUser user = new UUser();
        user.setName(claims.get("name", String.class));
        user.setPassword(claims.get("password", String.class));
        return user;
    }
}
